package cn.li.chatgpt.api.service;

import cn.li.chatgpt.api.AiServiceImp;
import cn.li.chatgpt.api.aimodel.req.MessageBody;
import cn.li.chatgpt.api.aimodel.vo.Messages;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
@Slf4j
public class AiService implements AiServiceImp {

    @Value("${data.apikey}")
    private String API_KEY;

    @Value("${data.secretkey}")
    private  String SECRET_KEY;

    @Override
    public String aiAnswer(String question) throws IOException {
        CloseableHttpClient client=HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/" +
                "wenxinworkshop/chat/completions?access_token=" + getAccessToken());
        post.setHeader("Content-Type", "application/json");
        List<Messages> list = new ArrayList<>();
        list.add(new Messages("user",question));
        MessageBody messageBody = new MessageBody(list);

//        String param = "{\"messages\":[{\"role\":\"user\",\"content\":\"你好\"}]}";
        String param = JSON.toJSONString(messageBody);
        log.info("请求参数：{}",param);
        StringEntity entity = new StringEntity(param,ContentType.create("application/json"));
        post.setEntity(entity);
        CloseableHttpResponse response = client.execute(post);
        if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
            return JSONObject.parseObject(EntityUtils.toString(response.getEntity())).getString("result");
        }else{
            throw new RuntimeException("访问错误："+response.getStatusLine().getStatusCode());
        }
    }

    @Override
    public String getAccessToken() throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("https://aip.baidubce.com/oauth/2.0/token");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        String param = "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
        StringEntity entity = new StringEntity(param, ContentType.create("application/x-www-form-urlencoded"));
        post.setEntity(entity);
        CloseableHttpResponse response = client.execute(post);
        if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            String access = JSONObject.parseObject(EntityUtils.toString(response.getEntity())).getString("access_token");
            log.info("access_token:{}",access);
            return access;
        }else {
            return null;
        }
    }
}
